import {Action, getModule, Module, Mutation, VuexModule} from 'vuex-module-decorators'
import {getToken, removeToken, setToken} from '@/core/utils/storage'
import {TagsViewModule} from './tags-view'
import store from '@/core/store'

export interface IUserState {
    name: any
    avatar: any
    introduction: any
    roles: []
    email: any
}

const data = {
    "user": {
        "id": 0,
        "username": "admin",
        "password": "any",
        "name": "Super Admin",
        "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
        "introduction": "I am a super administrator",
        "email": "admin@test.com",
        "phone": "1234567890",

    }
}

@Module({dynamic: true, store, name: 'user'})
class User extends VuexModule implements IUserState {
    public name = '';
    public avatar = '';
    public introduction = '';
    public roles: [] = [];
    public email = '';


    @Mutation
    private SET_NAME(name: any) {
        this.name = name
    }

    @Mutation
    private SET_AVATAR(avatar: any) {
        this.avatar = avatar
    }

    @Mutation
    private SET_INTRODUCTION(introduction: any) {
        this.introduction = introduction
    }

    @Mutation
    private SET_ROLES(roles: []) {
        this.roles = roles
    }

    @Mutation
    private SET_EMAIL(email: any) {
        this.email = email
    }


    @Action
    public ResetToken() {
        removeToken();
        setToken("");
        this.SET_ROLES([]);
    }

    @Action
    public async GetUserInfo() {
        const {name, avatar, introduction, email} = data.user;
        this.SET_ROLES(["admin"] as any);
        this.SET_NAME(name);
        this.SET_AVATAR(avatar);
        this.SET_INTRODUCTION(introduction);
        this.SET_EMAIL(email);
    }

    @Action
    public async ChangeRoles(role: any) {
        // Dynamically modify permissions
        const token = role + '-token'
        setToken(token)
        setToken(token)
        await this.GetUserInfo()
        // Generate dynamic accessible routes based on roles
        // PermissionModule.GenerateRoutes(this.roles)
        // Add generated routes
        // router.addRoutes(PermissionModule.dynamicRoutes)
        // Reset visited views and cached views
        TagsViewModule.delAllViews()
    }

    @Action
    public async LogOut() {
        if (getToken() === '') {
            throw Error('LogOut: token is undefined!')
        }
        removeToken()

        // Reset visited views and cached views
        TagsViewModule.delAllViews()
        setToken('')
        this.SET_ROLES([])
    }
}

export const UserModule = getModule(User)
